package com.freecloud.javabasics.thread.threadpool;

import com.freecloud.common.LoggerUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 固定线程数的线程池
 * @Author: maomao
 * @Date: 2020-03-04 16:03
 */
public class ThreadPoolDemo {

    public static void main(String[] args) {
        /** 固定线程数的线程池 */
        ExecutorService service = Executors.newFixedThreadPool(3);
        /** 只有一个线程的线程池 */
        ExecutorService service1 = Executors.newSingleThreadExecutor();
        /** 伸缩性，60秒回收 */
        ExecutorService service2 = Executors.newCachedThreadPool();
        /** 定时任务 */
        ExecutorService service3 = Executors.newScheduledThreadPool(3);
        /** fork/join线程池 */
        ExecutorService service4 = Executors.newWorkStealingPool();


        /**
         * 建议直接使用ThreadPoolExecutor创建线程池
         * 避免像newCachedThreadPool 的maximumPoolSize 为 Integer.MAX_VALUE造成OOM
         */
        for (int i = 0; i < 100; i++) {
            service4.execute(new TestTask());
        }
        service4.shutdown();
    }


    static class TestTask implements Runnable{
        @Override
        public void run() {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LoggerUtil.printThread();
        }
    }
}
